package com.turtle.learning.auth.service;

import com.turtle.learning.auth.dto.LoginUserInfo;
import com.turtle.learning.users.entity.User;
import com.turtle.learning.users.service.impl.UserServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证
 *
 * @author turtle
 * date: 2020-05-07
 */
@AllArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private final UserServiceImpl userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            log.error("登录用户{}不存在", username);
            throw new UsernameNotFoundException("登录用户" + username + "不存在，请联系管理员");
        }
        return LoginUserInfo.builder()
            .userId(user.getId())
            .username(user.getUsername())
            .user(user)
            .build();
    }
}
